package com.wn.icloud.common.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class CodeUtil {
    /**
     * 根据参数类型返回相应的编号
     * 1: 销售订单编号，
     * 2: 生产订单编号，
     * 3: 采购订单编号，
     * 4: 工单编号,
     * @return String code
     */
    public static String formatEnCode(int type){
        StringBuffer code = new StringBuffer();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dates = sdf.format(new Date());
        String times = (System.currentTimeMillis() / 1000) + "";
        String str = times.substring(0, times.length());
        if(1 == type){
            code.append("SO");
            code.append(dates);
            code.append(generateLetterNumToLength(3));
        }
        if(2 == type){
            code.append("PO");
            code.append(generateLetterStrToLength(1));
            code.append(str);
            code.append(generateLetterStrToLength(1));
        }
        if(3 == type){
            code.append("UO");
            code.append(generateLetterStrToLength(1));
            code.append(str);
            code.append(generateLetterStrToLength(1));
        }
        if(4 == type){
            code.append("WO");
            code.append(generateLetterStrToLength(2));
            code.append(str);
            code.append(generateLetterStrToLength(1));
        }
        return code.toString();
    }

    /**
     * 根据父级编号返回相应的子编号
     * @return
     */
    public static String formartSubEnCode(String parentCode){
        StringBuffer subCode = new StringBuffer();
        subCode.append(parentCode);
        subCode.append(".");
        subCode.append("B");
        return subCode.toString();
    }

    final static char[] letterCharUpper = {
            'A' , 'B' , 'C' , 'D' , 'E' , 'F' ,
            'G' , 'H' , 'I' , 'J' , 'K' , 'L' ,
            'M' , 'N' , 'O' , 'P' , 'Q' , 'R' ,
            'S' , 'T' , 'U' , 'V' , 'W' , 'X' ,
            'Y' , 'Z'
    };

    /**
     * 产生长度为length的随机字符串（只包括字母）
     * @param length	需要生成的字符串长度
     * @return
     */
    public static String generateLetterStrToLength(int length) {
        StringBuffer respStr = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            respStr.append(letterCharUpper[random.nextInt(26)]);
        }
        return respStr.toString();
    }

    /**
     * 产生长度为length的随机字符串（只包括字母）
     * @param length	需要生成的字符串长度
     * @return
     */
    public static String generateLetterNumToLength(int length) {
        StringBuffer respStr = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            respStr.append(random.nextInt(10));
        }
        return respStr.toString();
    }
}
